<template>
  <z-paging ref="paging" v-model="data.list" @query="getAreaList" refresher-enabled>
    <view class="c-pd">
      <view class="mb-3 c-br" v-for="(item, index) in data.list" :key="index">
        <van-panel>
          <view slot="header" class="c-pd">
            <view class="mb-1">{{ item.villageName }}</view>
            <view>
              <i class="c-text-color-grey i-basil:location-outline c-text-10"></i>
              <text class="c-text-color-grey c-text-12">{{ item.address }}</text>
            </view>
          </view>
          <view slot="footer" @click="applyCode(item.villageId)" class="justify-end flex items-center">
            <i class="i-ic:round-qrcode mx-1"></i>
            <text>生成申请码</text>
          </view>
        </van-panel>
      </view>
    </view>
  </z-paging>
  <van-popup :show="data.modelShow" position="bottom" custom-style="height: 50%">
    <van-picker show-toolbar confirm-button-text="确认" cancel-button-text="取消" value-key="modelName" :columns="data.modelList" @confirm="onModelChange" @cancel="onModelCancel" title="选择服务模版" />
  </van-popup>
</template>

<script setup lang="ts">
import UserRequest from '@/request/userRequest';
import useToast from '@/hooks/useToast';
import { useAppStore } from '@/store';

interface IData {
  pages: {
    pageNo: number;
    pageSize: number;
    totalPage: number;
  };
  list: IAreaList[];
  modelShow: boolean;
  modelList: IServerModelList[];
  villageId?: number;
}

const data = reactive<IData>({
  pages: {
    pageNo: 1,
    pageSize: 20,
    totalPage: 1,
  },
  list: [],
  modelShow: false,
  modelList: [],
  villageId: undefined,
});

const { showToast } = useToast();

const store = useAppStore();

const { userInfo } = store.$state;

const paging = ref();

const getAreaList = (pageNo: number, pageSize: number) => {
  UserRequest.GetAreaList({ pageNo, pageSize, hasLoading: true })
    .then((res) => {
      paging.value.complete(res.data.list);
    })
    .catch((err) => {
      paging.value.complete(false);
    });
};

const applyCode = (villageId: number) => {
  data.villageId = villageId;
  UserRequest.GetServerModel({ villageId }).then((res) => {
    if (res.status === 0) {
      data.modelList = res.data;
      if (data.modelList.length > 0) {
        data.modelShow = true;
      } else {
        showToast('暂无服务模版', 'error');
      }
    }
  });
};

//服务模版选择取消
const onModelCancel = (e: any) => {
  data.modelShow = false;
};

//服务模版选择
const onModelChange = (e: any) => {
  const { modelId } = e.detail.value;
  UserRequest.ApplyCode({
    serverModelId: modelId,
    userId: userInfo.userId,
    villageId: data.villageId,
    hasLoading: true,
  })
    .then((res) => {
      if (res.status === 0) {
        showToast('操作成功');
      }
    })
    .catch((err) => {
      showToast(err.msg);
    });
  data.modelShow = false;
};
</script>

<style lang="scss" scoped>
:deep(.van-panel) {
  border-radius: 16rpx;
}
</style>
